package com.cn.codebrush.线程;

public class 交替打印 {
    /**
     * 两个线程交替打印1-100
     * @param args
     */
    public static void main(String[] args) {
        /*PrintNumber1 printNumber = new PrintNumber1();*/

        PrintNumber2 printNumber = new PrintNumber2();
        Thread t1 = new Thread(printNumber,"线程1");
        Thread t2 = new Thread(printNumber,"线程2");
        //Thread t3 = new Thread(printNumber,"线程3");
        t1.start();
        t2.start();
        //t3.start();
    }


    /**
     * 使用类锁
     */
    static class PrintNumber1 implements Runnable{
        int i = 0;

        @Override
        public void run() {
            while (true){
                synchronized (this){
                    notify();
                    if(i<100){
                        i++;
                        System.out.println(Thread.currentThread().getName()+"--打印:"+i);
                    }else {
                        break;
                    }
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    /**
     * 使用对象锁
     */
    static class PrintNumber2 implements Runnable{

        int i =0;
        private  Object object = new Object();

        @Override
        public void run() {
            while (true){
                synchronized (object){
                    object.notify();
                    if(i<100){
                        i++;
                        System.out.println(Thread.currentThread().getName()+"--打印:"+i);
                    }else {
                        break;
                    }
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
